package reversi;

import java.util.ArrayList;
import java.util.List;


public class MaximinTree {

    public int value;
    public char color;
    public int[] move;
    public boolean is_leaf;
    public boolean is_Max_Node;
    public Board board;
    public ArrayList<MaximinTree> children;

    public MaximinTree(Board b, boolean max, int depth, char c) {
        board = new Board(b);
        children = new ArrayList<MaximinTree>();
        is_Max_Node = max;
        is_leaf = true;
        color =  c;
        if(depth > 0)
        	AddChildren(depth);
    }
    
    public void AddChildren(int depth){
    	ArrayList<int[]> move_list = board.listLegalMoves(color);
    	for(int i = 0; i < move_list.size(); i++){
    		Board temp = new Board(board);
    		temp.performMove(move_list.get(i)[0], move_list.get(i)[1], color);
	    	children.add(new MaximinTree(temp, !is_Max_Node, depth - 1, Get_Other_Color(color)));
	    	is_leaf = false;
    	}
    }

    public void Valuate(char c){
    	if(is_leaf){
	    	value = -99999;
			if(board.isGameOver()){
				if(board.whoWon() == c)
					value = 99999;		
			}
			else{
				value = board.Heuristic(c); //Returns the 'heuristic' value.  It's not technically a heuristic, 
										   //since it can be negative and it is large at the goal instead of small.
										   //It really just an evaluation function that ttries to take both mobility and 
										   //board position into account.
			}
    	}
    	else if(is_Max_Node){
    		int max_val = -10000;
    		int max_val_ind = 0;
    		for(int i = 0; i < children.size(); i++){
    			children.get(i).Valuate(c);
    			if( children.get(i).value > max_val){
    				max_val_ind = i;
    				max_val =children.get(i).value;
    			}
    		}
    		value = max_val;   		
    	}
    	
    	else{
    		int min_val = 10000;
    		int min_val_ind = 0;
    		for(int i = 0; i < children.size(); i++){
    			children.get(i).Valuate(c);
    			if( children.get(i).value < min_val){
    				min_val_ind = i;
    				min_val =children.get(i).value;
    			}
    		}
    		value = min_val;   		
    	}
    }
    
    char Get_Other_Color( char c){
    	if(c == 'W'){
    		return 'B';
    	}else if (c == 'B'){
    		return 'W';
    	}else{
    		System.out.println("Internal Engine Error: AI color comparing");
    		return c;
    	}
    }
    
}

